const app = '/lesson-admin';
onload = () => {

    let avatarIpt = document.querySelector('#avatarIpt');
    let avatarImg = document.querySelector('#avatarImg');
    let avatarLabel = document.querySelector('#avatarLabel');
    let uploadAvatarBtn = document.querySelector('#uploadAvatarBtn');

    // 分页查询用户数据
    pageUser(1,12);

    // 当上传控件变化时触发
    avatarIpt.onchange = e => preview(e.target.files[0], avatarImg, avatarLabel);

    // 当点击上传按钮时触发
    uploadAvatarBtn.onclick = () => uploadAvatar(avatarIpt.files[0]);
};

//分页查询用户数据
function pageUser(page, size) {
    ajax({
        'url': app + `/api/v1/user/page?page=${page}&size=${size}`,
        'success': res => {
            if (res.code < 1) {
                alert(res.message);
            }
            //查询成功
            else {
                console.log(res)
                //抓取响应数据
                let users = res.data['user-vos'];
                //抓取表格的Tbody
                let useTbody = document.querySelector('#userTbody');
                //将查询出来的数据渲染到表格之中
                renderUsers(users, useTbody);
                // 获取响应中的分页数据
                let page = res.data['page'];
                let size = res.data['size'];
                let pages = res.data['pages'];
                let total = res.data['total'];
                let pageNums = res.data['page-nums'];

                let pageUl = document.querySelector('#pageUl');

                // 将查询出来的分页数据渲染到分页列表中
                renderPage(page, size, pages, total, pageNums, pageUl);
            }
        }
    })
}
/*渲染用户数据到表格体*/
function renderUsers(users, userTbody) {

    // 每次添加数据之前都清空表格的全部内容，防止追加
    userTbody.innerHTML = '';

    let tr;
    for (let i = 0, j = users.length; i < j; i++) {
        tr = document.createElement('tr');
        tr.appendChild(createTd(`<input type="checkbox" value="${users[i]['user-id']}"/>`));
        tr.appendChild(createTd(i + 1 + ''));
        tr.appendChild(createTd(users[i]['username']));
        tr.appendChild(createTd(users[i]['nick-name']));
        tr.appendChild(createTd(users[i]['gender'] === 0 ?
            '女性' : users[i]['gender'] === 1 ? '男性' : '保密'));
        tr.appendChild(createTd(users[i]['age']));
        tr.appendChild(createTd(users[i]['real-name']));
        tr.appendChild(createTd(users[i]['id-card']));
        tr.appendChild(createTd(users[i]['phone']));
        let tailTd = createTd(`
                <button class="btn btn-link btn-sm text-info px-0">详情</button>
                <button class="btn btn-link btn-sm text-primary px-0">头像</button>
                <button class="btn btn-link btn-sm text-warning px-0">修改</button>
            `);
        tailTd.children[0].onclick = () => showDetail(users[i]);
        tailTd.children[1].onclick = () => showAvatar(users[i]);
        tailTd.children[2].onclick = () => update(users[i]);
        // 追加: td -> tr
        tr.appendChild(tailTd);
        // 追加: tr -> tbody
        userTbody.appendChild(tr);
    }
}

function renderPage(page, size, pages, total, pageNums, pageUl) {
    //每次添加数据之前都清空表格的内容，防止追加
    pageUl.innerHTML = '';
    let li;
    li = document.createElement('li');
    li.classList.add('page-item');
    li.innerHTML = `<a class="page-link" href="javascript:void(0)" onclick="pageUser(${page}-1,${size})">&laquo;</a>`
    //若当前页面为1则禁用上一页
    if (page<=1){
        li.classList.add('disabled');
    }


    pageUl.appendChild(li);

    for (let i=0;i<pageNums.length;i++){
        //数字页码
        li = document.createElement('li');
        li.innerHTML=`<a class="page-link" href="javascript:void(0)" onclick="pageUser(${i+1},${size})">${pageNums}</a>`;
        pageUl.appendChild(li);
        if (i+1===page){
            li.classList.add('active');
        }
    }
    //下一页
    li=document.createElement('li');
    li.classList.add('page-item');
    li.innerHTML = `<a class="page-link" href="javascript:void(0)" onclick="pageUser(${page}+1,${size})">&raquo;</a>`
    if (page<pages){
        li.classList.add('disabled');
    }
    pageUl.appendChild(li);

}
/*修改用户信息*/
function update(user){
    // 将当前点击的用户的全部数据存储起来
    sessionStorage.setItem('user', JSON.stringify(user));
    // 跳转到用户修改页面
    location.href = '../user/user-update.html';
}
/*批量删除用户信息*/
function batchDelete() {

    // 抓取表格的tbody
    let userTbody = document.querySelector('#userTbody');

    // 抓取表格中所有被选中的cbx
    let cbx = userTbody.querySelectorAll('input[type=checkbox]:checked');

    // 危险操作保护
    if (confirm(`将要删除 ${cbx.length} 条数据，确定吗？`)) {

        // 准备参数
        let userIds = [];
        cbx.forEach(cbx => userIds.push(cbx.value));

        // 管理员账号不允许删除
        if (userIds.indexOf('1') !== -1){
            alert('管理员账号不允许删除，请重新选择');
            return;
        }

        // 发送删除请求
        ajax({
            'url': app+ `/api/v1/user/delete-by-user-ids`,
            'type': 'post',
            'data': {'user-ids': userIds},
            'success': res => {
                if (res.code > 0) {
                    alert('删除成功!')
                    location.href = '../user/user.html';
                } else alert(res.message);
            }
        });
    }
}
/*上传头像*/
function uploadAvatar(avatarFile) {

    // 校验头像文件
    if (!avatarFile) {
        alert('上传失败: 未选择图片!')
        return false
    }

    // 准备请求参数
    let avatarImg = document.querySelector('#avatarImg');
    let data = {
        'avatar-file': avatarFile,
        'user-id': avatarImg.value
    };

    // 发送上传头像请求
    ajax({
        'url': APP + '/api/v1/user/upload-avatar',
        'type': 'post',
        'contentType': 'file',
        'data': data,
        'success': res => {
            if (res.code > 0) {
                alert('上传成功!')
                location.href = '../user/user.html';
            } else alert(res.message);
        }
    });
}
/*打印报表*/
function excel() {
    if(confirm('即将导出全部用户数据，确定吗')){
        location.href = 'http://localhost:8080/lesson-admin/api/v1/user/excel';
        alert('导出成功！')
    }
}
/*展示用户头像*/
function showAvatar(user) {
    let avatarImg = document.querySelector('#avatarImg');
    avatarImg.src = MINIO_BUCKET + '/avatar/' + user['avatar-url'];
    // 利用自定义属性，存储一下用户ID
    avatarImg.value = user['user-id'];
    // 利用JQ代码将模态框展示出来
    $('#userAvatarModal').modal('show');
}
/*展示用户详细信息*/
function showDetail(user) {
    let usernameMsg = document.querySelector('#usernameMsg');
    let nickNameMsg = document.querySelector('#nickNameMsg');
    let genderMsg = document.querySelector('#genderMsg');
    let ageMsg = document.querySelector('#ageMsg');
    let realNameMsg = document.querySelector('#realNameMsg');
    let idCardMsg = document.querySelector('#idCardMsg');
    let phoneMsg = document.querySelector('#phoneMsg');
    let avatarUrlMsg = document.querySelector('#avatarUrlMsg');
    let createTimeMsg = document.querySelector('#createTimeMsg');
    let modifyTimeMsg = document.querySelector('#modifyTimeMsg');
    let userInfoMsg = document.querySelector('#userInfoMsg');
    // 赋值
    usernameMsg.innerHTML = user['username'];
    nickNameMsg.innerHTML = user['nick-name'];
    genderMsg.innerHTML = user['gender'] === 0 ? '女性' :
        user['gender'] === 1 ? '男性' : '保密';
    ageMsg.innerHTML = user['age'];
    realNameMsg.innerHTML = user['real-name'];
    idCardMsg.innerHTML = user['id-card'];
    phoneMsg.innerHTML = user['phone'];
    avatarUrlMsg.innerHTML = user['avatar-url'];
    createTimeMsg.innerHTML = user['create-time'];
    modifyTimeMsg.innerHTML = user['modify-time'];
    userInfoMsg.innerHTML = user['user-info'] || '暂无信息';

    // 利用JQ代码将模态框展示出来
    $('#userDetailModal').modal('show');
}


